package com.example.docking.controller;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.request.CommonOperateDao;
import com.example.docking.dao.jindie.response.InvPickData;
import com.example.docking.dao.jindie.response.InvPickDetailData;
import com.example.docking.dao.jindie.response.MaterialEntity;
import com.example.docking.dao.jindie.response.SaveData;
import com.example.docking.service.impl.DataServiceImpl;
import com.example.docking.util.Constants;
import com.example.docking.util.TimeRangeMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author: tengguodong
 * @date: 2025/5/15
 */
@Slf4j
@Controller
public class InvPickController {
    private static final Logger logger = LoggerFactory.getLogger(InvPickController.class);

    private Gson gson = new Gson();

    private PurOrderController purOrderController = new PurOrderController();

    /**
     * 1.查询生产领料列表
     * 2.查询生产领料详情（得到生产任务单编号）
     * 3.根据生产领料商品编码查询采购申请单
     * 4.查询采购申请单详情
     * 5.采购申请单备注匹配生产任务单编号，根据采购申请单判断外采外购外协
     * 6.推送到敬信完工
     */
    public ResponseData SelectInvPick() {
        logger.info("监控生产领料单");
        try {
            // 1.查询生产领料列表
            List<InvPickData> invPickDataList = getInvPickDataList();
            for (InvPickData invPickData : invPickDataList) {
                // 2.查询生产领料详情
                InvPickDetailData invPickDetailData = selectById(invPickData.getId());
                if ("推送敬信成功".equals(invPickDetailData.getRemark())) {
                    continue;
                }
                List<MaterialEntity> materialEntity = invPickDetailData.getMaterial_entity();
                // 根据采购申请单推送敬信
                boolean success = true;
                for (MaterialEntity entity : materialEntity) {
                    boolean result = purOrderController.SelectPurOrder(entity.getSrc_bill_no(), entity.getMaterial_number());
                    success = success && result;
                    // 如果有任何一个失败，可以提前退出循环
                    if (!success) {
                        break;
                    }
                }
                if (success) {
                    logger.info("推送成功");
                    // 反审核生产领料单
                    unAuditInvPick(invPickData.getId());

                    // 保存生产领料单
                    invPickDetailData.setRemark("推送敬信成功");
                    new DataServiceImpl().UpdateData(Constants.INV_PICK, new HashMap<>(), invPickDetailData);

                    // 审核生产领料单
                    auditInvPick(invPickData.getId(), new DataServiceImpl());
                } else {
                    logger.info("推送失败");
                }
            }
        } catch (Exception e) {
            logger.error("查询采购订单时发生异常", e);
            throw new RuntimeException(e);
        }
        return new ResponseData();
    }

    /**
     * 采购订单审核
     *
     * @param id
     * @param service
     */
    private void auditInvPick(String id, DataServiceImpl service) {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        CommonOperateDao commonOperateDao = new CommonOperateDao();
        commonOperateDao.setEntity_number(Constants.INV_PICK_BILL);
        commonOperateDao.setIds(ids);
        commonOperateDao.setOperate_type(Constants.AUDIT);
        try {
            ApiResult auditData = service.SelectDataAudit(Constants.COMMON_OPERATE, new HashMap<>(), commonOperateDao);
            ResponseData<SaveData> auditResponse = gson.fromJson(auditData.getBody(), new TypeToken<ResponseData<SaveData>>() {
            }.getType());
            if (auditResponse.getErrcode() == 0) {
                log.info("审核生产领料单成功, auditResponse = {}", auditResponse);
            } else {
                log.error("审核生产领料单失败. auditResponse: {}", auditResponse);
                throw new RuntimeException(auditResponse.getErrcode() + ":" + auditResponse.getDescription());
            }
        } catch (Exception e) {
            log.error("Error occurred while auditing sales order", e);
            throw new RuntimeException(e);
        }
    }

    private void unAuditInvPick(String id) {
        DataServiceImpl dataService = new DataServiceImpl();
        List<String> ids = new ArrayList<>();
        ids.add(id);
        HashMap<String, String> map = new HashMap<>();
        log.info("反审核：生产领料单ids: {}", ids);
        CommonOperateDao commonOperateDao = new CommonOperateDao();
        commonOperateDao.setEntity_number(Constants.INV_PICK_BILL);
        commonOperateDao.setIds(ids);
        commonOperateDao.setOperate_type(Constants.UNAUDIT);
        ResponseData<SaveData> response = null;
        try {
            ApiResult auditData = dataService.SelectDataAudit(Constants.COMMON_OPERATE, map, commonOperateDao);
            response = gson.fromJson(auditData.getBody(), new TypeToken<ResponseData<SaveData>>() {
            }.getType());
            if (response.getErrcode() == 0) {
                log.info("反审核：审核生产领料成功");
            } else {
                log.error("反审核：审核生产领料单失败. auditResponse: {}", response);
            }
        } catch (Exception e) {
            log.error("反审核：Error occurred while auditing sales order", e);
        }
    }

    private List<InvPickData> getInvPickDataList() {
        List<InvPickData> invPickDataList;
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        map.put("bill_status", "C");
        //创建时间-结束时间的时间戳(毫秒)
        TimeRangeMap timeRangeMap = new TimeRangeMap();
        map.put("modify_start_time", timeRangeMap.getDayStartTime()); //    创建时间-开始时间的时间戳(毫秒)
        map.put("modify_end_time", timeRangeMap.getDayEndTime()); //  	创建时间-结束时间的时间戳(毫秒)
        ApiResult DataResult;
        try {
            DataServiceImpl Service = new DataServiceImpl();
            DataResult = Service.SelectDataList(Constants.INV_PICK, map, "");

            Type DataType = new TypeToken<ResponseData<GenericDataItem<InvPickData>>>() {
            }.getType();
            ResponseData<GenericDataItem<InvPickData>> responseData = gson.fromJson(DataResult.getBody(), DataType);
            logger.info("查询返回code:" + responseData.getErrcode());
            logger.info("查询返回description:" + responseData.getDescription());
            GenericDataItem<InvPickData> genericDataItem = responseData.getData();
            // 解析分页信息
            String count = genericDataItem.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<InvPickData> Data = genericDataItem.getRows();

            invPickDataList = new ArrayList<>(Data);
            // 如果不是最后一页，继续获取下一页数据
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                DataResult = Service.SelectDataList(Constants.INV_PICK, map, "");
                responseData = gson.fromJson(DataResult.getBody(), DataType);
                genericDataItem = responseData.getData();
                Data = genericDataItem.getRows();
                invPickDataList.addAll(Data);
                Pagesum = (pageSize * page);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return invPickDataList;
    }

    private InvPickDetailData selectById(String id) {
        InvPickDetailData invPickDetailData;
        Gson gson = new Gson();
        logger.info("根据编号获取采购订单");
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        DataServiceImpl Service = new DataServiceImpl();
        ApiResult DataResult = null;
        try {
            DataResult = Service.SelectDataList(Constants.INV_PICK_DETAIL, map, "");
            Type SaleDataType = new TypeToken<ResponseData<InvPickDetailData>>() {
            }.getType();
            ResponseData<InvPickDetailData> responseSaleData = gson.fromJson(DataResult.getBody(), SaleDataType);
            invPickDetailData = responseSaleData.getData();
            logger.info("code" + responseSaleData.getErrcode());
            logger.info("描述" + responseSaleData.getDescription());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return invPickDetailData;
    }

    /**
     * 根据领料单详情获取生产任务单号
     *
     * @param invPickDetailData
     * @return
     */
    private String getOrderCode(InvPickDetailData invPickDetailData) {
        List<MaterialEntity> materialEntityList = invPickDetailData.getMaterial_entity();
        if (materialEntityList == null || materialEntityList.isEmpty()) {
            return null;
        }
        return materialEntityList.get(0).getSrc_bill_no();
    }

    public static void main(String[] args) {
        InvPickController invPickController = new InvPickController();
        invPickController.SelectInvPick();
    }
}
